package com.lichuandi.spring;

import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * A simple dependency injection container.
 * 依赖注入模拟
 */
public class SimpleDIContainer {
    private Map<String, Object> beans = new HashMap<>();

    public void registerBean(String name, Object bean) {
        beans.put(name, bean);
    }

    public Object getBean(String name) {
        return beans.get(name);
    }

    public void autowireBeans() throws Exception {
        for (Object bean : beans.values()) {
            Class<?> clazz = bean.getClass();
            for (Field field : clazz.getDeclaredFields()) {
                if (field.isAnnotationPresent(Autowired.class)) {
                    field.setAccessible(true);
                    Object dependency = beans.get(field.getType().getSimpleName());
                    if (dependency != null) {
                        field.set(bean, dependency);
                    }
                }
            }
        }
    }
}